<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ace Editor 自动补全示例</title>
    <!-- 引入 Ace Editor 的 CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ext-language_tools.js"></script>
</head>
<body>
    <div id="editor" style="height: 500px; width: 100%;"></div>

    <script>
        // 初始化 Ace Editor
        const editor = ace.edit("editor");
        editor.setTheme("ace/theme/monokai");
        editor.session.setMode("ace/mode/sql");

        // 启用自动补全
        ace.require("ace/ext/language_tools").setCompleters([]);
        editor.setOptions({
            enableBasicAutocompletion: true,
            enableLiveAutocompletion: true,
        });

        // 模拟的本地数据库表名
        const mockDatabaseTables = {
            "database1": ["table1", "table2", "table3"],
            "database2": ["table4", "table5", "table6"]
        };

        // 当前使用的数据库名
        let currentDatabaseName = null;

        // 定义自定义补全器
        const customCompleter = {
            getCompletions: function(editor, session, pos, prefix, callback) {
                // 获取当前行内容
                const cursorPosition = editor.getCursorPosition();
                const currentLine = session.getLine(cursorPosition.row);

                // 匹配数据库名（假设数据库名称以某种方式标识，例如前缀或某种格式）
                const dbNameMatch = currentLine.match(/\b(\w+)\b/i);
                if (dbNameMatch) {
                    currentDatabaseName = dbNameMatch[1];
                }

                // 获取当前数据库的表名
                const tables = currentDatabaseName ? (mockDatabaseTables[currentDatabaseName] || []) : [];
                const completions = tables.map(tableName => ({
                    caption: tableName,
                    value: tableName,
                    meta: "table"
                }));
                callback(null, completions);
            }
        };

        // 将自定义补全器添加到 Ace Editor
        editor.completers = [customCompleter];

        // 监听内容更改事件
        editor.session.on('change', function(delta) {
            // 打印更改内容（可选）
            console.log("Editor content changed:", delta);
            // 手动触发自动补全提示
            editor.execCommand("startAutocomplete");
        });
    </script>
</body>
</html>
